package com.sharp.mq.service.delay;

import com.rabbitmq.client.Channel;
import com.sharp.mq.bo.RabbitMqMessage;
import com.sharp.mq.service.RabbitMqService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.stereotype.Service;
import org.springframework.util.concurrent.ListenableFutureCallback;

import javax.annotation.Resource;
import java.io.IOException;

import static com.sharp.mq.config.RabbitDelayMessageConfig.DELAY_MESSAGE_EXCHANGE_NAME;
import static com.sharp.mq.config.RabbitDelayMessageConfig.DELAY_MESSAGE_ROUTER_KEY;

/**
 * Title: RabbitDelayMessageService
 * Description: Copyright: Copyright (c) 2019 Company: BHFAE
 *
 * @author Sharp
 * @date 2021/7/2 17:59
 */
@Slf4j
@Service
// @RabbitListener(queues = {DELAY_MESSAGE_PLUGIN_QUEUE_NAME, DELAY_MESSAGE_QUEUE_NAME})
public class RabbitDelayMessageService {

    @Resource
    private RabbitMqService rabbitMqService;

    public <T> void send(T message, long delay, ListenableFutureCallback<T> callback) {
        RabbitMqMessage rabbitMqMessage = new RabbitMqMessage();
        // rabbitMqMessage.setExchangeName(DELAY_MESSAGE_PLUGIN_EXCHANGE_NAME);
        rabbitMqMessage.setExchangeName(DELAY_MESSAGE_EXCHANGE_NAME);
        rabbitMqMessage.setRouterKey(DELAY_MESSAGE_ROUTER_KEY);
        rabbitMqMessage.setBody(message);
        rabbitMqMessage.setDelay(delay);
        rabbitMqMessage.setCallback(callback);
        rabbitMqService.sendMessageAsync(rabbitMqMessage);
    }

    // @RabbitHandler
    public Object handle(Object dto, Channel channel, Message message) throws IOException {

        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            return dto;
        } catch (Exception e) {
            channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
            return dto;
        }
    }
}
